
Rule.cpf = function( value ){

	var sum,remain,y;
	
	if( !value ){ 
		return true;
	}
	
	var sum = 0;

	value = value.replace(".","").replace(".","").replace("-","");

	if (value.length != 11 || 
		value == "00000000000" || 
		value == "11111111111" || 
		value == "22222222222" ||
		value == "33333333333" || 
		value == "44444444444" || 
		value == "55555555555" || 
		value == "66666666666" || 
		value == "77777777777" || 
		value == "88888888888" || 
		value == "99999999999"
	)
	{
		 return false;
	}
	
	for (y=0; y < 9; y ++){
		sum += parseInt(value.charAt(y)) * (10 - y);
	}
	
	remain = 11 - (sum % 11);
	
	if (remain == 10 || remain == 11){
		remain = 0;
	}
	
	if (remain != parseInt( value.charAt(9) ) ){
		return false;
	}
	 
	sum = 0;
	
	for (y = 0; y < 10; y ++){
		sum += parseInt( value.charAt(y) ) * (11 - y);
	}
	
	remain = 11 - (sum % 11);
	
	if (remain == 10 || remain == 11){ 
		remain = 0;
	}
	
	if ( remain != parseInt( value.charAt(10) ) ){
		return false;
	}

	return true;
}

Rule.cpf.mask = function( id ){
    $('#'+id).unmask().mask("999.999.999-99");
}

Rule.cnpj = function( value ){
	var n = [],sum,result;
	
	if( !value ){
		return true;
	}

	value = value.replace(".","").replace(".","").replace("/","").replace("-","");

	if ( value == "00000000000000" ){
		return false;
	}

	n.push( 0 );

	for( var i = 0; i < value.length; i++  ){
		n.push( parseInt( value.substr( i , 1 ) ) );
	}
	
	var sum = ( n[1] * 5 ) + ( n[2] * 4 ) + ( n[3] * 3 ) + ( n[4] * 2 ) + ( n[5] * 9 ) + ( n[6] * 8 ) + ( n[7] * 7 ) +	( n[8] * 6 ) + ( n[9] * 5 ) + ( n[10] * 4 ) + ( n[11] * 3 ) + ( n[12] * 2 );
	
	sum = sum - ( 11 * ( parseInt( sum / 11 ) ) );
	
	if( sum == 0 || sum == 1 ){
		result = 0;
	}else{
		result = 11 - sum;
	}
	
	
	if( result == n[13] ){
		sum = n[1] * 6 + n[2] * 5 + n[3] * 4 + n[4] * 3 + n[5] * 2 + n[6] * 9 + n[7] * 8 + n[8] * 7 + n[9] * 6 + n[10] * 5 + n[11] * 4 + n[12] * 3 + n[13] * 2;
		sum = sum - ( 11 * ( parseInt( sum/11 ) ) );

		if ( sum == 0 || sum == 1 ){
			result = 0;
		}else{
			result = 11 - sum;
		}
		
		if( result == n[14] ){
			return true;
		}
	}
	
	return false;
}

Rule.cnpj.mask = function( id )
{
    $('#'+id).unmask().mask("99.999.999/9999-99");
}

Rule.fone = function( value )
{
    if( !value ){
    	return true;
    }
	return /^\d{4}\-\d{4}$/.test(value);
}

Rule.fone.mask = function( id )
{
    $('#'+id).unmask().mask("9999-9999");
}

Rule.cep = function( value )
{
    if( !value ){
    	return true;
    }
	return /^\d{5}\-\d{3}$/.test(value);
}

Rule.cep.mask = function( id )
{
    $('#'+id).unmask().mask("99999-999");
}
